//
//  UploadManager.swift
//  ezyform
//
//  Created by Moennig Q on 2/6/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import Foundation
import HandyJSON
enum FlushUploadType: String {
    case finishJob = "1"
    case panelInstalled = "2"
    case flushUpload = "3"
}
var reuploadDataType: String = ""//"1": finish job ; "2": panel installed; "3": reupload
class UploadManager {
    let semphore = DispatchSemaphore(value: 0)
    static let shared = UploadManager()
    //MARK: - 上传Image,或pdf类型的 noc或other attachment
    func uploadAttachment(imageModel: CheckListImageDBModel, closure: ((Bool)->Void)? = nil){
        guard let dbID = DBManager.shared.getChecklistImageByRecordAt(imageModel) else{
            return
        }
        imageModel.dbId = dbID
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (resultStr , _) -> Void in
                //1.删除
                DBManager.shared.deleteChecklistImageData(model: imageModel)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newDetailModel = JSONDeserializer<PVDDetailModel>.deserializeFrom(json: resultStr as? String) {
                        if imageModel.checklist_id == ChecklistFixedId.nocAttachment.rawValue{//Noc附件
                            JobDetailModelHelper.shared.jobDetailModel.notice_of_completion_documents = newDetailModel.notice_of_completion_documents
                        }else if imageModel.checklist_id == ChecklistFixedId.otherAttachment.rawValue{//Other 附件
                            JobDetailModelHelper.shared.jobDetailModel.other_document = newDetailModel.other_document
                        }
                        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists = newDetailModel.pvd_checklists
                        JobDetailModelHelper.shared.jobDetailModel.dealAndGetLocalChecklist()
                        //刷新当前的checklist
                        if let checklist = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.first(where: {$0.id == imageModel.checklist_id}){
                            if imageModel.pvd_id == JobDetailModelHelper.shared.checklistModel.pvdId && JobDetailModelHelper.shared.checklistModel.id == imageModel.checklist_id{//如果当前的checklist依然是现在正在上传的checklist，则刷新当前的list
                                JobDetailModelHelper.shared.checklistModel = checklist
                                JobDetailModelHelper.shared.checklistModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
                            }
                        }
                    }
                    
                    closure?(true)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                closure?(false)
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "1")
            }
            
            checklistVM.uploadAttachment(imageModel)
            
            self.semphore.wait()
        }
    }
    //MARK: - 删除 noc或other attachment
    func deleteAttachment(imageModel: CheckListImageDBModel, closure: ((Bool)->Void)? = nil){
        guard let dbID = DBManager.shared.getChecklistImageByRecordAt(imageModel) else{
            return
        }
        imageModel.dbId = dbID
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (result , _) -> Void in
                //1.删除
                DBManager.shared.deleteChecklistImageData(model: imageModel)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newDetailModel = result as? PVDDetailModel {
                        if imageModel.checklist_id == ChecklistFixedId.nocAttachment.rawValue{//Noc附件
                            JobDetailModelHelper.shared.jobDetailModel.notice_of_completion_documents = newDetailModel.notice_of_completion_documents
                        }else if imageModel.checklist_id == ChecklistFixedId.otherAttachment.rawValue{//Other 附件
                            JobDetailModelHelper.shared.jobDetailModel.other_document = newDetailModel.other_document
                        }
                        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists = newDetailModel.pvd_checklists
                        JobDetailModelHelper.shared.jobDetailModel.dealAndGetLocalChecklist()
                    }
                    
                    closure?(true)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                closure?(false)
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "1")
            }
            
            checklistVM.deleteAttachment(imageModel)
            
            self.semphore.wait()
        }
    }
    //MARK: - 上传Image类型的 checklist
    func uploadChecklistImage(imageModel: CheckListImageDBModel, closure: ((Bool)->Void)? = nil){
        guard let dbID = DBManager.shared.getChecklistImageByRecordAt(imageModel) else{
            return
        }
        imageModel.dbId = dbID
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (resultStr , _) -> Void in
                //1.删除
                DBManager.shared.deleteChecklistImageData(model: imageModel)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newChecklist = (JSONDeserializer<PVDChecklistModel>.deserializeModelArrayFrom(json: resultStr as? String) as? Array<PVDChecklistModel>){
                        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists = newChecklist
                        JobDetailModelHelper.shared.jobDetailModel.dealAndGetLocalChecklist()
                        //刷新当前的checklist
                        if let checklist = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.first(where: {$0.id == imageModel.checklist_id}){
                            if imageModel.pvd_id == JobDetailModelHelper.shared.checklistModel.pvdId && JobDetailModelHelper.shared.checklistModel.id == imageModel.checklist_id{//如果当前的checklist依然是现在正在上传的checklist，则刷新当前的list
                                JobDetailModelHelper.shared.checklistModel = checklist
                                JobDetailModelHelper.shared.checklistModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
                            }
                        }
                    }
                    
                    closure?(true)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                closure?(false)
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(checklistImage_table_name, keyId: imageModel.dbId, flag: "1")
            }
            checklistVM.uploadChecklistImage(imageModel: imageModel)
            self.semphore.wait()
        }
    }
    //MARK: - 上传Image类型的 checklist
    func uploadServiceChecklistImage(imageModel: CheckListImageDBModel, closure: ((Bool)->Void)? = nil){
        guard let dbID = DBManager.shared.getChecklistImageByRecordAt(imageModel, jobType: .serviceJob) else{
            return
        }
        imageModel.dbId = dbID
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (resultStr , _) -> Void in
                //1.删除
                DBManager.shared.deleteServiceChecklistImageData(model: imageModel)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newChecklist = (JSONDeserializer<PVDChecklistModel>.deserializeModelArrayFrom(json: resultStr as? String) as? Array<PVDChecklistModel>){
                        ServiceDetailModelHelper.shared.serviceDetailModel.checklists = newChecklist
                        ServiceDetailModelHelper.shared.serviceDetailModel.dealAndGetLocalChecklist()
                        //刷新model
                        if let currentChecklist = ServiceDetailModelHelper.shared.serviceDetailModel.checklists.first(where: {$0.id == imageModel.checklist_id}){
                            if imageModel.pvd_id == ServiceDetailModelHelper.shared.checklistModel.pvdId && JobDetailModelHelper.shared.checklistModel.id == imageModel.checklist_id{//如果当前的checklist依然是现在正在上传的checklist，则刷新当前的list(防止多个checklist快速操作，图片混乱)
                                ServiceDetailModelHelper.shared.checklistModel = currentChecklist
                            }
                        }
                    }
                    
                    closure?(true)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                closure?(false)
                DBManager.shared.setUpoadingFlag(service_checklistImage_table_name, keyId: imageModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(service_checklistImage_table_name, keyId: imageModel.dbId, flag: "1")
            }
            checklistVM.uploadChecklistImage(imageModel: imageModel,jobType: .serviceJob)
            self.semphore.wait()
        }
    }
    //MARK: - 上传pvd job的bool或text类型的 checklist
    func uploadChecklistBoolOrText(checklistModel: PVDChecklistModel){
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (resultStr , _) -> Void in
                //1.删除
                
                DBManager.shared.deleteChecklsitData(pvdId: JobDetailModelHelper.shared.jobDetailModel.id, checklistId: checklistModel.id)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newChecklist = (JSONDeserializer<PVDChecklistModel>.deserializeModelArrayFrom(json: resultStr as? String) as? Array<PVDChecklistModel>){
                        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists = newChecklist
                        JobDetailModelHelper.shared.jobDetailModel.dealAndGetLocalChecklist()
                    }
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                DBManager.shared.setUpoadingFlag(checklist_table_name, keyId: checklistModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(checklist_table_name, keyId: checklistModel.dbId, flag: "1")
            }
            checklistVM.uploadChecklistBoolOrText(checklistModel: checklistModel)
            self.semphore.wait()
        }
    }
    //MARK: - 上传service job 的bool或text类型的 checklist
    func uploadServiceChecklistBoolOrText(checklistModel: PVDChecklistModel){
        GlobalOperationQueue.addOperation {
            let checklistVM = JobDetailService()
            checklistVM.setBlockAfterNetwork({ (resultStr , _) -> Void in
                //1.删除
                
                DBManager.shared.deleteChecklsitData(pvdId: ServiceDetailModelHelper.shared.serviceDetailModel.serviceID, checklistId: checklistModel.id, jobType: .serviceJob)
                
                //2.通知刷新数据
                DispatchQueue.main.async {
                    if let newChecklist = (JSONDeserializer<PVDChecklistModel>.deserializeModelArrayFrom(json: resultStr as? String) as? Array<PVDChecklistModel>){
                        ServiceDetailModelHelper.shared.serviceDetailModel.checklists = newChecklist
                        ServiceDetailModelHelper.shared.serviceDetailModel.dealAndGetLocalChecklist()
                    }
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                DBManager.shared.setUpoadingFlag(service_checklist_table_name, keyId: checklistModel.dbId, flag: "0")
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlag(service_checklist_table_name, keyId: checklistModel.dbId, flag: "1")
            }
            checklistVM.uploadChecklistBoolOrText(checklistModel: checklistModel,jobType: .serviceJob)
            self.semphore.wait()
        }
    }
    //MARK: - 增加，修改，删除一个panel
    //closure不为空，表示有回到处理
    func uploadOnePanelNumber(_ localPanel: PanelNumberImageDBModel, closure: ((Bool, PanelNumberImageDBModel?)->Void)? = nil){
        GlobalOperationQueue.addOperation {
            let panelNumberVM = JobDetailService()
            //set block
            panelNumberVM.setBlockAfterNetwork({ (result , _) -> Void in
                DispatchQueue.main.async {
                    DBManager.shared.deleteLocalBarcodeByCode(tableName: panelnumber_table_name, code: localPanel.code)
                    var returnModel = localPanel
                    if let resutList = JSONDeserializer<PanelNumberImageDBModel>.deserializeModelArrayFrom(json: result as? String) {
                        if let list = resutList as? Array<PanelNumberImageDBModel>{
                            JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers = list
                            //处理本地数据，且同时数据刷新
                            JobDetailModelHelper.shared.jobDetailModel.getLocalPanelNumber()
                            //此处用于刷新扫描界面上的list数据的是否上传的状态
                            if localPanel.operType == DataOperType.Add.rawValue {
                                if let index = list.firstIndex(where: {$0.code == localPanel.code}){
                                    returnModel = list[index]
                                }
                            }
                        }
                    }
                    closure?(true, returnModel)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                DispatchQueue.main.async {
                    DBManager.shared.setUpoadingFlagForBarcode(panelnumber_table_name, code: localPanel.code, flag: "0")
                    closure?(false, nil)
                }
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlagForBarcode(panelnumber_table_name, code: localPanel.code, flag: "1")
            }
            panelNumberVM.uploadSerialsNumber(localPanel,type: .panel)
            self.semphore.wait()
        }
    }
    //MARK: - 增加，修改，删除一个inverter或panel
    //closure不为空，表示有回到处理
    func uploadOneInverterNumber(_ localPanel: PanelNumberImageDBModel, closure: ((Bool,PanelNumberImageDBModel?)->Void)? = nil){
        GlobalOperationQueue.addOperation {
            let panelNumberVM = JobDetailService()
            //set block
            panelNumberVM.setBlockAfterNetwork({ (result , _) -> Void in
                DispatchQueue.main.async {
                    DBManager.shared.deleteLocalBarcodeByCode(tableName: inverternumber_table_name, code: localPanel.code)
                    var returnModel = localPanel
                    if let resutList = JSONDeserializer<PanelNumberImageDBModel>.deserializeModelArrayFrom(json: result as? String) {
                        if let list = resutList as? Array<PanelNumberImageDBModel>{
                            JobDetailModelHelper.shared.jobDetailModel.pvd_inverter_serial_numbers = list
                            //处理本地数据，且同时数据刷新
                            JobDetailModelHelper.shared.jobDetailModel.getLocalInverterNumber()
                            //此处用于刷新扫描界面上的list数据的是否上传的状态
                            if localPanel.operType == DataOperType.Add.rawValue {
                                if let index = list.firstIndex(where: {$0.code == localPanel.code}){
                                    returnModel = list[index]
                                }
                            }
                        }
                    }
                    closure?(true, returnModel)
                }
                self.semphore.signal()
            }) { (code, error) -> Void in
                DispatchQueue.main.async {
                    DBManager.shared.setUpoadingFlagForBarcode(inverternumber_table_name, code: localPanel.code , flag: "0")
                    closure?(false, nil)
                }
                self.semphore.signal()
            }
            DispatchQueue.main.async {
                DBManager.shared.setUpoadingFlagForBarcode(inverternumber_table_name, code: localPanel.code, flag: "1")
            }
            panelNumberVM.uploadSerialsNumber(localPanel,type: (JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? .tank : .inverter))
            self.semphore.wait()
        }
    }
    //MARK: 按照pvd job一个个上传本地数据
    //uploadingClosure：本地数据上传过程中的closure
    func uploadLocalDataByPVDJob(_ pvdId: String, uploadingClosure: ((Int32,Int32,Int32)->Void)? = nil){
        var uploadedSuccessCount: Int32 = 0//已经上传成功的
        var uploadedFaildCount: Int32 = 0//上传失败的
        let needUploadCnt: Int32 = self.getTotalCntOfLocalData(pvdId)
        if needUploadCnt == 0 || !Connectivity.isConnectedToInternet{//没有数据上传，或者没有网络就不上传
            return
        }
        //0.先取消所有的网络请求
        Tool().cancelAllNetworkRequestForPVD()
        //1.获取本地数据
        let checklistArray: [PVDChecklistModel] = DBManager.shared.loadAllChecklistData(pvdId: pvdId)
        let localSerialNumbers: [PanelNumberImageDBModel] = DBManager.shared.loadLocalSeriallNumber(pvdId: pvdId,tableName: panelnumber_table_name)
        let localInverterNumbers: [PanelNumberImageDBModel] = DBManager.shared.loadLocalSeriallNumber(pvdId: pvdId,tableName: inverternumber_table_name)
        let signatureArray: [SignatureImageDBModel] = DBManager.shared.loadAllSignatueData(pvdId)
        //初始化view的
        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
        //1.checklist
        for localModel in checklistArray {
            //图片类型
            if localModel.type == ChecklistType.Image.rawValue {
                let totalImageList = localModel.localAddImages + localModel.localDeletedImages
                for imageModel in totalImageList{
                    GlobalOperationQueue.addOperation {
                        DBManager.shared.setUpoadingFlag(checklistImage_table_name,keyId: localModel.dbId, flag: "1")
                        let checklistVM = JobDetailService()
                        checklistVM.setBlockAfterNetwork({ (result , _) -> Void in
                            DBManager.shared.deleteChecklistImageData(model: imageModel)
                            DispatchQueue.main.async {
                                uploadedSuccessCount += 1
                                uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                            }
                            self.semphore.signal()
                            
                        }) { (code, error) -> Void in
                            DBManager.shared.setUpoadingFlag(checklistImage_table_name,keyId: localModel.dbId, flag: "0")
                            self.semphore.signal()
                            DispatchQueue.main.async {
                                uploadedFaildCount += 1
                                uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                            }
                        }
                        //noc， other attachment 特别处理
                        if localModel.id == ChecklistFixedId.otherAttachment.rawValue || localModel.id == ChecklistFixedId.nocAttachment.rawValue{
                            if imageModel.oper_type == DataOperType.Add.rawValue {//增加
                                checklistVM.uploadAttachment(imageModel)
                            }else{//删除
                                checklistVM.deleteAttachment(imageModel)
                            }
                        }else{
                            checklistVM.uploadChecklistImage(imageModel: imageModel)
                        }
                        
                        self.semphore.wait()
                    }
                }
                
            }else{//text,bool
                GlobalOperationQueue.addOperation {
                    DBManager.shared.setUpoadingFlag(checklist_table_name,keyId: localModel.dbId, flag: "1")
                    //
                    let checklistVM = JobDetailService()
                    checklistVM.setBlockAfterNetwork({ (result , _) -> Void in
                        DBManager.shared.deleteChecklsitData(pvdId: "\(pvdId)", checklistId: localModel.id)
                        DispatchQueue.main.async {
                            uploadedSuccessCount += 1
                            uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                        }
                        self.semphore.signal()
                        
                    }) { (code, error) -> Void in
                        
                        DBManager.shared.setUpoadingFlag(checklist_table_name,keyId: localModel.dbId, flag: "0")
                        self.semphore.signal()
                        DispatchQueue.main.async {
                            uploadedFaildCount += 1
                            uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                        }
                    }
                    
                    checklistVM.uploadChecklistBoolOrText(checklistModel: localModel)
                    self.semphore.wait()
                }
                
            }
        }
        //2.panel number
        for localPanel in localSerialNumbers {
            GlobalOperationQueue.addOperation {
                DBManager.shared.setUpoadingFlag(panelnumber_table_name, keyId: localPanel.dbId, flag: "1")
                //
                let panelNumberVM = JobDetailService()
                //set block
                panelNumberVM.setBlockAfterNetwork({ (result , _) -> Void in
                    DBManager.shared.deleteLocalBarcodeByCode(tableName: panelnumber_table_name, code: localPanel.code)
                    DispatchQueue.main.async {
                        uploadedSuccessCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                    self.semphore.signal()
                    
                    
                }) { (code, error) -> Void in
                    
                    if error == RequestErrorType.NetworkError.rawValue{//网络问题
                        DBManager.shared.setUpoadingFlag(panelnumber_table_name, keyId: localPanel.dbId, flag: "0")
                    }else{//API错误
                        if error.contains(localPanel.code) && error.contains("deleted") {
                            DBManager.shared.deleteLocalBarcodeByCode(tableName: panelnumber_table_name, code: localPanel.code)
                        }else{//上传出问题，继续保存到本地
                            DBManager.shared.setUpoadingFlag(panelnumber_table_name, keyId: localPanel.dbId, flag: "0")
                        }
                    }
                    self.semphore.signal()
                    DispatchQueue.main.async {
                        uploadedFaildCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                }
                
                panelNumberVM.uploadSerialsNumber(localPanel, type: .panel)
                self.semphore.wait()
            }
        }
        
        //2.inverter number
        for localInverter in localInverterNumbers {
            GlobalOperationQueue.addOperation {
                DBManager.shared.setUpoadingFlag(inverternumber_table_name, keyId: localInverter.dbId, flag: "1")
                //
                let panelNumberVM = JobDetailService()
                //set block
                panelNumberVM.setBlockAfterNetwork({ (result , _) -> Void in
                    DBManager.shared.deleteLocalBarcodeByCode(tableName: inverternumber_table_name, code: localInverter.code)
                    DispatchQueue.main.async {
                        uploadedSuccessCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                    self.semphore.signal()
                    
                    
                }) { (code, error) -> Void in
                    if error == RequestErrorType.NetworkError.rawValue{
                        DBManager.shared.setUpoadingFlag(inverternumber_table_name, keyId: localInverter.dbId, flag: "0")
                    }else{
                        //如果返回的信息是Can not find this panel number, it may have been deleted, number: xxxxx，就是这个barcode已经被其他用户删除了，此时要删除本地数据
                        if error.contains(localInverter.code) && error.contains("deleted") {
                            DBManager.shared.deleteLocalBarcodeByCode(tableName: inverternumber_table_name, code: localInverter.code)
                        }else{//上传出问题，继续保存到本地
                            DBManager.shared.setUpoadingFlag(inverternumber_table_name, keyId: localInverter.dbId, flag: "0")
                        }
                    }
                    
                    self.semphore.signal()
                    DispatchQueue.main.async {
                        uploadedFaildCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                }
                
                panelNumberVM.uploadSerialsNumber(localInverter, type: (JobDetailModelHelper.shared.jobDetailModel.solar_water_heater ? .tank : .inverter))
                self.semphore.wait()
            }
        }
        //3.signature
        for localModel in signatureArray {
            GlobalOperationQueue.addOperation {
                DBManager.shared.setUpoadingFlag(signature_table_name, keyId: localModel.dbId, flag: "1")
                
                let signaturesVM = JobDetailService()
                signaturesVM.setBlockAfterNetwork({ (result , _) -> Void in
                    DBManager.shared.deleteLocalSignatureByDBId(tableName: signature_table_name, keyId: localModel.dbId)
                    DispatchQueue.main.async {
                        uploadedSuccessCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                    self.semphore.signal()
                }) { (code, error) -> Void in
                    
                    DBManager.shared.setUpoadingFlag(signature_table_name, keyId: localModel.dbId, flag: "0")
                    self.semphore.signal()
                    DispatchQueue.main.async {
                        uploadedFaildCount += 1
                        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                    }
                    
                }
                
                signaturesVM.uploadSignatures(localModel)
                self.semphore.wait()
            }
        }
    }
    //MARK: 按照service job一个个上传本地数据
    //uploadingClosure：本地数据上传过程中的closure
    func uploadLocalDataByServiceJob(_ serviceId: String, uploadingClosure: ((Int32,Int32,Int32)->Void)? = nil){
        var uploadedSuccessCount: Int32 = 0//已经上传成功的
        var uploadedFaildCount: Int32 = 0//上传失败的
        let needUploadCnt: Int32 = self.getServiceTotalCntOfLocalData(serviceId)
        if needUploadCnt == 0 || !Connectivity.isConnectedToInternet{//没有数据上传，或者没有网络就不上传
            return
        }
        //0.先取消所有的网络请求
        Tool().cancelAllNetworkRequestForService()
        //1.获取本地数据
        let checklistArray: [PVDChecklistModel] = DBManager.shared.loadAllServiceChecklistData(serviceId: serviceId)
        //初始化view的
        uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
        //1.checklist
        for localModel in checklistArray {
            //图片类型
            if localModel.type == ChecklistType.Image.rawValue {
                let totalImageList = localModel.localAddImages + localModel.localDeletedImages
                for imageModel in totalImageList{
                    GlobalOperationQueue.addOperation {
                        DBManager.shared.setUpoadingFlag(service_checklistImage_table_name,keyId: localModel.dbId, flag: "1")
                        let checklistVM = JobDetailService()
                        checklistVM.setBlockAfterNetwork({ (result , _) -> Void in
                            DBManager.shared.deleteServiceChecklistImageData(model: imageModel)
                            self.semphore.signal()
                            DispatchQueue.main.async {
                                uploadedSuccessCount += 1
                                uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                            }
                            
                        }) { (code, error) -> Void in
                            DBManager.shared.setUpoadingFlag(service_checklistImage_table_name,keyId: localModel.dbId, flag: "0")
                            self.semphore.signal()
                            DispatchQueue.main.async {
                                uploadedFaildCount += 1
                                uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                            }
                        }
                        checklistVM.uploadChecklistImage(imageModel: imageModel,jobType: .serviceJob)
                        
                        self.semphore.wait()
                    }
                }
                
            }else{//text,bool
                GlobalOperationQueue.addOperation {
                    DBManager.shared.setUpoadingFlag(service_checklist_table_name,keyId: localModel.dbId, flag: "1")
                    let checklistVM = JobDetailService()
                    checklistVM.setBlockAfterNetwork({ (result , _) -> Void in
                        DBManager.shared.deleteChecklsitData(pvdId: "\(serviceId)", checklistId: localModel.id, jobType: .serviceJob)
                        self.semphore.signal()
                        DispatchQueue.main.async {
                            uploadedSuccessCount += 1
                            uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                        }
                        
                    }) { (code, error) -> Void in
                        DBManager.shared.setUpoadingFlag(service_checklist_table_name,keyId: localModel.dbId, flag: "0")
                        self.semphore.signal()
                        DispatchQueue.main.async {
                            uploadedFaildCount += 1
                            uploadingClosure?(needUploadCnt,uploadedSuccessCount,uploadedFaildCount)
                        }
                    }
                    
                    checklistVM.uploadChecklistBoolOrText(checklistModel: localModel,jobType: .serviceJob)
                    self.semphore.wait()
                }
                
            }
        }
    }
    //MARK: - 取消上传flush upload
    func cancelFlushUpload(){//1.先取消所有的网络请求
        Tool().cancelAllNetworkRequestForPVD()
    }
    
    //MARK: - 获取本地未上传的数量
    func getTotalCntOfLocalData(_ pvdId: String)->Int32{
        let localSerialNumbers: [PanelNumberImageDBModel] = DBManager.shared.loadLocalSeriallNumber(pvdId: pvdId,tableName: panelnumber_table_name)
        let localInverterNumbers: [PanelNumberImageDBModel] = DBManager.shared.loadLocalSeriallNumber(pvdId: pvdId,tableName: inverternumber_table_name)
        let signatureArray: [SignatureImageDBModel] = DBManager.shared.loadAllSignatueData(pvdId)
        //获取checklist本地数量，image，text，bool
        let checklistCount: Int32 = DBManager.shared.getLocalChecklistDataCount(pvdId: pvdId)
        //
        let totalCnt = checklistCount + Int32(localSerialNumbers.count  + localInverterNumbers.count + signatureArray.count)
        return totalCnt
    }
    //MARK: - 获取servcie本地未上传的数量
    func getServiceTotalCntOfLocalData(_ serviceId: String)->Int32{
        //获取checklist本地数量，image，text，bool
        let checklistCount: Int32 = DBManager.shared.getServiceLocalDataCount(serviceId: serviceId)
        
        return checklistCount
    }
}
